#include "captchasolver.h"
#include <QDebug>
#include <QTcpSocket>
#include <QDate>
#include "clientsocket.h"

CaptchaSolver* CaptchaSolver::instance = NULL;

CaptchaSolver* CaptchaSolver::getInstance(){
    if(instance==NULL)
        instance=new CaptchaSolver();
    return instance;
};

CaptchaSolver::CaptchaSolver()
{
    server=new QTcpServer;
    server->listen(QHostAddress::Any, 2200);
    if(!server->isListening()){
        qDebug()<<"Nie mozna sie zbundiwac ";
        exit(0);
    }
    connect(server, SIGNAL(newConnection()),
            this, SLOT(newConnection()));
};

int CaptchaSolver::solve(QString address){
    CaptchaDesc *desc=new CaptchaDesc(address);
    list.insert(desc->getHash(), desc);
    if(cliList.count()==0){
        qDebug()<<"Waiting for client";
    }
    foreach(ClientSocket* cli, cliList){

        //qDebug()<<"Sending path to: "<<cli->connDetails();
        cli->question(desc);

    }
    return desc->getHash();
};



void CaptchaSolver::newConnection(){
    ClientSocket* con=new ClientSocket(server->nextPendingConnection());
    connect(con, SIGNAL(toBeDeleted(ClientSocket*)), this, SLOT(removeClient(ClientSocket*)));
    connect(con, SIGNAL(solved(int,QString)), this, SLOT(solvedSlot(int, QString)));

    cliList.append(con);
    qDebug()<<"New client"<<QDate::currentDate();
    foreach(CaptchaDesc *desc, list){
        con->question(desc);
    }
}

void CaptchaSolver::removeClient(ClientSocket* cli){
    qDebug()<<"Removing client"<<QDate::currentDate();;
    cliList.removeOne(cli);
}

void CaptchaSolver::solvedSlot(int hash, QString caption){
    //qDebug()<< __FILE__<<":"<<__LINE__<<"\tSolved:"<<QString().number(hash)<<caption;
    emit solved(hash, caption);
}

CaptchaDesc* CaptchaSolver::getCaptchaDesc(int hash){
    //qDebug()<< __FILE__<<":"<<__LINE__<<"looking for:"<<QString().number(hash);
    if(!list.contains(hash)){
        //qDebug()<< __FILE__<<":"<<__LINE__<<"no such hash"<<QString().number(hash);
        return NULL;
    }

    QMap<int,CaptchaDesc*>::const_iterator i = list.constBegin();
    while (i != list.constEnd()) {
        //qDebug()<< __FILE__<<":"<<__LINE__ << i.key() << ": " << ((CaptchaDesc*)i.value())->getHash() << endl;
        ++i;
    }

    return list.value(hash);
};

void CaptchaSolver::rmCaptchaDesc(int hash){
    list.remove(hash);
   // qDebug()<<"removing captcha from stack"<<QString().number(hash);
};

CaptchaSolver::~CaptchaSolver(){
    delete instance;
    delete server;
    foreach(CaptchaDesc *desc, list){
        delete desc;
    }

}
